package org.example.struct.array2;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyishan
 * @date 2023/10/8 09:10
 * @apiNote
 */

public class Test00228SummaryRanges {

    public static void main(String[] args) {
        int[] nums = {0,2,3,4,6,8,9};
        List<String> result = test(nums);
        System.out.println(JSON.toJSON(result));
    }

    public static List<String> test(int[] nums) {
        List<String>  result = new ArrayList<>();
        int start = 0;
        for(int i = 0; i < nums.length; i++){
            if(i+1 == nums.length ||nums[i+1] - nums[i] != 1){
                if(nums[start] == nums[i]){
                    result.add(String.valueOf(nums[start]));
                }else{
                    result.add(nums[start] + "->" + nums[i]);
                }
                start = i+1;
            }
        }
        return result;
    }

    public static List<String> test1(int[] nums) {
        List<String>  result = new ArrayList<>();
        if(nums.length == 0){
            return result;
        }
        int start = nums[0];
        for(int i = 0; i < nums.length; i++){
            if(i+1 == nums.length){
                if(start == nums[i]){
                    result.add(String.valueOf(start));
                }else{
                    result.add(start + "->" + nums[i]);
                }
            }else if(nums[i+1] - nums[i] != 1){
                if(start == nums[i]){
                    result.add(String.valueOf(start));
                }else{
                    result.add(start + "->" + nums[i]);
                }
                start = nums[i+1];
            }
        }
        return result;
    }


    public static List<String> test2(int[] nums) {
        List<String> ans = new ArrayList<String>();
        int i = 0;
        for (int j = 0; j < nums.length; j++) {
            if (j + 1 == nums.length || nums[j] + 1 != nums[j + 1]) {
                StringBuilder sb = new StringBuilder();
                sb.append(nums[i]);
                if (i != j) {
                    sb.append("->").append(nums[j]);
                }
                ans.add(sb.toString());
                i = j + 1;
            }
        }
        return ans;
    }
}
